package database;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import messages.MessageLoginReply.AccountType;
import messages.MessageLoginReply.ErrMsg;
import messages.MessageLoginReply.LoginStatus;
import messages.MessageLoginReply.Permission;
import sharedspace.*;



/**
 * This class checks if the user details are correct and give back the user details
 * @author Amir S.
 * @author Jacob C.
 * @author Maya G.
 * @author Michael V.
 *
 */
public class LoginCheck {
	
	private User userLog;
	private ErrMsg error;

	int[] retStatus;

	
	
	/**
	 * 
	 * @param User user
	
	 */
	public LoginCheck(User user)
	{
		userLog = user;
	}

	/**
	 * This method checks if the user details are correct and give back all it's details
	 */
	public void Check() 
	{
		
		
			String userID = userLog.getUserID();

			String userPassword = userLog.getUserPassword();

			
			
		
		Object[] result = new Object[User.NUM_OF_COLUMNS];
		if (JDBC.existStatment(userID, "u.userID", "aes.users u") == true)
		{		
			JDBC.selectStatment("SELECT * FROM users u Where u.userID="+userID +";", result, User.NUM_OF_COLUMNS);
			for (int i=0; i<User.NUM_OF_COLUMNS;i++){
				if (result[i].toString().isEmpty()) {
					this.error=ErrMsg.UNKNOWN;
					return;
				}
			}
			userLog.setUserID(result[0].toString());
			userLog.setUserLastName(result[1].toString());
			userLog.setUserFirstName(result[2].toString());
			userLog.setUserPassword(result[3].toString());
			userLog.setUserPermission(Integer.parseInt(result[4].toString()));
			userLog.setUserLogged(Boolean.parseBoolean(result[5].toString()));
			userLog.setUserStatus(result[6].toString());
			
			if (userLog.getUserPassword().equals(userPassword))
			{
				if (userLog.getUserLogged() == false)
				{
				this.error=ErrMsg.SUCCESS;
				userLog.setUserLogged(true);
				JDBC.insertStatment("UPDATE users SET users.userLogged=1 WHERE aes.users.userId="+userLog.getUserID());
				System.out.println("User: " + userLog.getUserPassword() + " has logged in successfuly.");
				}
				else this.error=ErrMsg.ALREADY_LOGIN;
			}
			else this.error=ErrMsg.INCORRECT;
		
			
		
		}
		else {
			System.out.println("not exist");
			this.error=ErrMsg.UNKNOWN;
			
		}
	}

	/**
	 * 
	 * @return Error Message
	 */
	public ErrMsg getErrorMessage()
	{
		return error;
	}
	
    /**
     * 
     * @return User userLog
     */
	public User getUser()
	{
		return userLog;
	}
	
}

